package com.jianying.day08;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: Flink01_KeyedState_ValueState_1
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/9 09:40
 * @Version: 1.0
 */
public class Flink04_KeyedState_MapState {
    public static void main(String[] args) throws Exception {
        // TODO 统计每种传感器，每个水位值出现次数
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> mapDS = env.socketTextStream("localhost", 8888)
                .map(new WaterSensorMapFunction());

        // TODO 按键分组 ID
        KeyedStream<WaterSensor, String> keyByDS = mapDS.keyBy(WaterSensor::getId);

        // TODO 分组后数据处理
       keyByDS.process(
               new KeyedProcessFunction<String, WaterSensor, String>() {
                   MapState<Integer, Integer> vcMapState;

                   @Override
                   public void open(Configuration parameters) throws Exception {
                       MapStateDescriptor<Integer, Integer> mapStateDescriptor = new MapStateDescriptor<Integer, Integer>("vcMapState", Integer.class, Integer.class);
                       vcMapState = getRuntimeContext().getMapState(mapStateDescriptor);
                   }

                   @Override
                   public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                       Integer vc = value.getVc();
                       // 判断状态里有没有
                       if(vcMapState.contains(vc)) {
                           vcMapState.put(vc, vcMapState.get(vc) + 1);
                       } else {
                           vcMapState.put(vc,1);
                       }

                       StringBuilder outStr = new StringBuilder();
                       outStr.append("--------------" + '\n');
                       outStr.append("传感器id:" + value.getId() + '\n');
                       for (Map.Entry<Integer, Integer> entry : vcMapState.entries()) {
                           outStr.append(entry.toString() + '\n');
                       }
                        out.collect(outStr.toString());
                   }
               }
       ).printToErr();

        env.execute();
    }
}
